#include "centerform.h"
#include "databasemanager.h"
#include "progressitemdelegate.h"
#include "downloadmanager.h"
#include "databasemanager.h"
#include "icondelegate.h"
#include <QDebug>
#include <QLabel>
#include <QHeaderView>

CenterForm::CenterForm(QWidget *parent) :
    QWidget(parent)
{
    table = new QTableView(this);

    QGridLayout* myLayout = new QGridLayout();
    myLayout->setColumnStretch(0,10);
    setLayout(myLayout);
    myLayout->addWidget(table);

    DatabaseManager::getDBManager();
    tableModel = new QSqlTableModel(this);
    tableModel->setTable("download");
    tableModel->select();

    table->setItemDelegateForColumn(3, new ProgressItemDelegate(this));
    table->setItemDelegateForColumn(4, new IconDelegate(this));
    table->setModel(tableModel);

    dataMapper = new QDataWidgetMapper(this);
    dataMapper->setModel(tableModel);
    dataMapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
    dataMapper->setItemDelegate(new QSqlRelationalDelegate(dataMapper));
    table->setSortingEnabled(TRUE);
    table->setAlternatingRowColors(TRUE);
    table->setSelectionMode(QAbstractItemView::SingleSelection);
    table->setSelectionBehavior(QAbstractItemView::SelectRows);
    table->setEditTriggers(QAbstractItemView::NoEditTriggers);
    table->resizeColumnsToContents();

    connect(table->verticalHeader(),SIGNAL(sectionClicked(int)),this,SLOT(deleteRaw(int)));

    //start old downloads
    for(size_t i = 0; i < tableModel->rowCount(); ++i)
    {
        if (tableModel->data(tableModel->index(i, 3)).toInt() == 100) continue;
        DownloadManager *download = new DownloadManager();
        connect(download, SIGNAL(progressUpdate()), this, SLOT(dataUpdate()));
        int id = DatabaseManager::getDBManager()->insertProgressDownload(tableModel->data(tableModel->index(i, 0)).toInt(),0);
        download->startDownload(tableModel->data(tableModel->index(i, 1)).toString(), tableModel->data(tableModel->index(i, 2)).toString(), tableModel->data(tableModel->index(i, 4)).toInt(), id);
    }

    dataMapper->toFirst();
}

void CenterForm::show()
{
    QModelIndex curIndex = table->currentIndex();
    tableModel->select();
    table->setCurrentIndex(curIndex);
}

void CenterForm::dataUpdate()
{
    show();
}

CenterForm::~CenterForm()
{
    delete table;
}

void CenterForm::deleteRaw(int index)
{
    DatabaseManager::getDBManager()->deleteDownload(tableModel->data(tableModel->index(index, 0)).toInt());
    show();
}
